package com.woniuxy.enjoylife.interceptors;

import com.woniuxy.enjoylife.anno.HasRole;
import com.woniuxy.enjoylife.mapper.UserMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

//请求权限拦截器
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        // 获取token
        String token = null;
        token = request.getHeader("token");
        //通过token得到账号信息

        if (null != token && token.length() != 0) {
            int id = (int) redisTemplate.opsForValue().get(token);
            request.getSession().setAttribute("id", id);
        }
        //获取到要请求的方法
//        if (handler instanceof HandlerMethod) {
//            HandlerMethod handlerMethod = (HandlerMethod) handler;
//            Method method = handlerMethod.getMethod();
//            //获取方法上的注解
//            if (method.isAnnotationPresent(HasRole.class)) {
//                //获取注解value值
//                HasRole hasRole = method.getAnnotation(HasRole.class);
//                //根据注解值判断获取权限名
//                String perm = hasRole.value();
//
//                if (perm != null && perm.length() != 0) {
//                    //获取用户所有的权限
//                    List<String> perms = userMapper.selectUserPerms(id);
//                    //判断是否有权限
//                    return perms.contains(perm);
//                }
//            }
//        }

        return super.preHandle(request, response, handler);
    }
}
